package com.king.camera.scan.config;

import android.content.Context;
import android.util.DisplayMetrics;

import androidx.annotation.NonNull;
import androidx.camera.core.CameraSelector;

/**
 * 相机配置工厂类：主要用于创建CameraConfig，提供相对简单的创建方式
 *
 * @author <a href="mailto:jenly1314@gmail.com">Jenly</a>
 */
public final class CameraConfigFactory {

    private CameraConfigFactory() {
        throw new AssertionError();
    }

    /**
     * 根据设备配置创建一个相匹配的CameraConfig；主要根据设备屏幕的分辨率找到比屏幕分辨率小一级的配置；
     * 在适配、性能与体验之间找到平衡点，最终创建一个比较适合当前设备的 CameraConfig。
     *
     * @param context    {@link Context}
     * @param lensFacing {@link CameraSelector#LENS_FACING_BACK} or {@link CameraSelector#LENS_FACING_FRONT}
     * @return
     */
    public static CameraConfig createDefaultCameraConfig(Context context, int lensFacing) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        int size = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels);
        // 根据分辨率初始化缺省配置CameraConfig；在此前提下尽可能的找到比屏幕分辨率小一级的配置；在适配、性能与体验之间得有所取舍，找到平衡点。
        if (size > ResolutionCameraConfig.IMAGE_QUALITY_720P) {
            int imageQuality = ResolutionCameraConfig.IMAGE_QUALITY_720P;
            if (size > ResolutionCameraConfig.IMAGE_QUALITY_1080P) {
                imageQuality = ResolutionCameraConfig.IMAGE_QUALITY_1080P;
            }
            return new ResolutionCameraConfig(context, imageQuality) {
                @NonNull
                @Override
                public CameraSelector options(@NonNull CameraSelector.Builder builder) {
                    if (lensFacing >= 0) {
                        builder.requireLensFacing(lensFacing);
                    }
                    return super.options(builder);
                }
            };
        } else {
            return new AspectRatioCameraConfig(context) {
                @NonNull
                @Override
                public CameraSelector options(@NonNull CameraSelector.Builder builder) {
                    if (lensFacing >= 0) {
                        builder.requireLensFacing(lensFacing);
                    }
                    return super.options(builder);
                }
            };
        }
    }
}
